package org.wdh.extend.visitor;

import java.io.OutputStream;
import java.io.PrintStream;

class TreePrinter implements TreeVisitor {
	private int amountOfIndentation;

	// The stream to which we are printing.
	PrintStream out;

	public TreePrinter() {
		this.amountOfIndentation = 0;
		this.out = System.out;
	}

	public TreePrinter(OutputStream _out) {
		this();
		this.out = new PrintStream(_out);
	}

	TreePrinter(int _amountOfIndentation) {
		this();
		this.amountOfIndentation = _amountOfIndentation;
	}

	TreePrinter(int _amountOfIndentation, OutputStream _out) {
		this();
		this.amountOfIndentation = _amountOfIndentation;
		this.out = new PrintStream(_out);
	}

	// factory method
	TreePrinter newTree(int _amountOfIndentation, OutputStream _out) {
		return new TreePrinter(_amountOfIndentation, _out);
	}

	/**
	 * Prints an amount of whitespace proportional to the current degree of
	 * indentation.
	 */
	public void indent() {
		for (int i = 0; i < this.amountOfIndentation; i++) {
			this.out.print("....");
		}
	}

	public Object forLeaf(Leaf that) {
		// Since leaves are empty, they are not printed.
		// Returns a dummy object to satisfy TreeVisitor interface.
		return new Object();
	}

	public Object forBranch(Branch that) {
		/*TreePrinter innerPrinter = new TreePrinter(
				this.amountOfIndentation + 1, this.out);*/
		TreePrinter innerPrinter = newTree(this.amountOfIndentation + 1, this.out);
		this.indent();
		this.out.println(that.getValue());
		that.getLeft().accept(innerPrinter);
		that.getRight().accept(innerPrinter);
		// Returns a dummy object to satisfy TreeVisitor interface.
		return new Object();
	}
}
